package com.tf.pemporaryfood.controller;

import com.tf.pemporaryfood.domain.entity.Goods;
import com.tf.pemporaryfood.service.GoodsService;
import com.tf.pemporaryfood.util.ApiResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RequestMapping("goods")
@Controller
@RestController
public class GoodsController {

    @Autowired
    private GoodsService goodsService;

    /**
     * 根据关键字或分类id搜索商品
     * @param query
     * @param cateId
     * @param page
     * @param limit
     * @return
     */
    @RequestMapping("search")
    public ApiResult<Object> search(String query, Integer cateId, Integer page, Integer limit) {
//        System.out.println(query.length());
        //获取商品总条数
        Long total = goodsService.getTotal(query, cateId);
        //获取所有商品
        List<Goods> goodsList = goodsService.search(query, cateId, (long) ((page - 1) * limit), limit);
//        System.out.println(goodsList);
        Map<String, Object> data = new HashMap(){{
            put("total", total);
            put("page", page);
            put("goods", goodsList);
        }};
        return ApiResult.ok(data);
    }

    /**
     * 根据商品id获取单个商品的信息
     * @param goodsId
     * @return
     */
    @RequestMapping("getInfo")
    public ApiResult<Goods> getInfo(Long goodsId){
        Goods goods = goodsService.getInfo(goodsId);
        return ApiResult.ok(goods);
    }
}
